/**
 * 
 */
package com.faxsun.web.controller.admin;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import mblog.core.planet.PostPlanet;
import mblog.core.pojos.Post;
import mblog.core.pojos.Tag;
import mblog.core.utils.BeanMapUtils;
import mblog.web.controller.BaseController;
import mtons.modules.pojos.Data;
import mtons.modules.pojos.Page;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faxsun.core.pojos.enums.PostType;
import com.faxsun.core.pojos.enums.TagType;
import com.faxsun.core.service.PostService;
import com.faxsun.core.service.TagService;
import com.faxsun.pojos.view.PostTable;
import com.faxsun.web.controller.admin.url.AdminViewConstants;

/**
 * @author langhsu
 * @author songdragon
 *
 */
@Controller
@RequestMapping("/admin/posts")
public class PostsManageController extends BaseController {
	@Autowired
	private PostService postService;
	@Autowired
	private PostPlanet postPlanet;

	@Autowired
	private TagService tagService;

	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public String view(@ModelAttribute("blog") Post blog,
			@RequestParam(value = "type", required = false) Integer type,
			@RequestParam(value = "id", required = false) Long id,
			ModelMap model) {
		if (type == null) {
			type = PostType.EVALUATION.getValue();
		}
		blog.setType(type);
		if (id != null && id > 0L) {
			Post p = postPlanet.getPost(id);
			blog = (p == null ? blog : p);
		}
		// 列出产品标签
		Page productPage = new Page(0);
		tagService.listTags(TagType.PRODUCT, productPage);
		@SuppressWarnings("unchecked")
		List<Tag> tags = (List<Tag>) productPage.getResults();
		tags.add(new Tag());
		model.addAttribute(AdminViewConstants.ATTR_POST_PRODUCT_TAG, tags);

		model.addAttribute(AdminViewConstants.VIEW,
				AdminViewConstants.VIEW_POST_ADD);
		model.addAttribute("blog", blog);
		return AdminViewConstants.VIEW_ADMIN_LAYOUT;
	}

	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String post(@ModelAttribute("blog") Post blog,
			BindingResult bindingResult, HttpServletRequest request) {
		// FIXME:优化Tag的处理方式
		String view = "redirect:/admin/posts/list";
		if (blog != null) {
			String url = blog.getSnapshot().getOriginal();
			String contextPath = request.getContextPath();
			if (!url.startsWith(contextPath) && !StringUtils.isEmpty(url) // url以非context
																			// path相对路径开始且非空
					&& !url.startsWith("http://") // url非绝对路径
					&& !url.startsWith("https://")) {
				// url为非当前context下的相对路径,则增加context path
				url = contextPath + url;
				blog.getSnapshot().setOriginal(url);
			}
			if (url.equals(contextPath)) {
				// url 仅包含当前context path
				blog.getSnapshot().setOriginal("");
			}
			postPlanet.post(blog);
			view += "?type=" + blog.getType();
		}
		return view;
	}

	@RequestMapping("/list")
	public String list(
			@RequestParam(value = "type", required = false) Integer type,
			ModelMap model) {
		// Page page = wrapPage(pn);
		// postService.paging(page);
		// model.put("page", page);
		String url = "/admin/posts/data-url";
		if (type != null) {
			url += "?type=" + type;
			model.addAttribute("type", type);
		}
		model.addAttribute("url", url);
		model.addAttribute(AdminViewConstants.VIEW,
				AdminViewConstants.VIEW_POST_LIST);

		return AdminViewConstants.VIEW_ADMIN_LAYOUT;
	}

	@RequestMapping("/view")
	public String view(Long id, ModelMap model) {
		Post ret = postService.get(id);
		model.put("view", ret);
		return "/admin/posts/view";
	}

	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public @ResponseBody Data delete(@PathVariable Long id) {
		Data data = Data.failure("操作失败");
		if (id != null) {
			try {
				postPlanet.delete(id);
				data = Data.success("操作成功");
			} catch (Exception e) {
				data = Data.failure(e.getMessage());
			}
		}
		return data;
	}

	/**
	 * JSON获取Post列表数据
	 * 
	 * @param type
	 * @param pageNo
	 * @param max
	 * @param search
	 * @param field
	 * @param model
	 * @return
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "/data-url", method = RequestMethod.GET)
	public @ResponseBody PostTableJSON data(
			@RequestParam(value = "type", required = false) Integer type,
			@RequestParam(value = "offset", required = false) Integer pageNo,
			@RequestParam(value = "limit", required = false) Integer max,
			@RequestParam(value = "search", required = false) String search,
			@RequestParam(value = "sort", required = false) String field,
			ModelMap model) {
		// 参数校验及转换
		PostType postType = PostType.parse(type);
		if (pageNo == null) {
			pageNo = 1;
		}
		if (max == null) {
			max = 10;
		}
		pageNo = pageNo / max + 1;
		Page page = wrapPage(pageNo);
		page.setMaxResults(max);

		// TODO:按字段排序
		if (StringUtils.isEmpty(search)) {
			postService.pagingByStatus(page, postType, -1);
		} else {
			// TODO:搜索结果
		}
		PostTableJSON ret = new PostTableJSON();
		ret.total = page.getTotalCount();
		ArrayList<PostTable> table = new ArrayList<PostTable>();
		for (Post post : (List<Post>) page.getResults()) {
			table.add(BeanMapUtils.copy(post));
		}
		ret.rows = table;
		return ret;
	}

}

class PostTableJSON {
	public int total;
	public List<PostTable> rows;

}